package main

import (
	"encoding/binary"
	"fmt"
	"io/ioutil"
	"net"

	"flag"
	"net/http"
	_ "net/http/pprof"
	"os"
)

func main() {
	flagset := flag.NewFlagSet("parameters", flag.ExitOnError)
	var sAddr string
	flagset.StringVar(&sAddr, "s", "", "server address, e.g. 127.0.0.1:3131")
	flagset.Parse(os.Args[1:])

	go http.ListenAndServe("0.0.0.0:6365", nil)
	l, err := net.Listen("tcp4", sAddr)
	var f, _ = l.(*net.TCPListener).File()
	f.F
	if err != nil {
		panic(err)
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			panic(err)
		}
		go handleConn(conn)
	}
}

func handleConn(conn net.Conn) {
	var err error
	defer func() {
		conn.Close()
		fmt.Println("exit handle....", err)
	}()

	lenBtes := make([]byte, 4)
	_, err = conn.Read(lenBtes)
	if err != nil {
		fmt.Println(err)
		return
	}
	length := binary.BigEndian.Uint32(lenBtes)
	data := make([]byte, length)
	offset := 0
	fmt.Println("read length", length)
	var n int
	for {
		n, err = conn.Read(data[offset:])
		if err != nil {
			fmt.Println(offset, n, err)
			return
		}
		offset += n
		if offset == len(data) {
			break
		} else {
			fmt.Println("read ", n, " bytes. offset ", offset)
		}
	}

	err = ioutil.WriteFile("/tmp/tcp_up."+conn.RemoteAddr().String()+".mp3", data, 0666)
	if err != nil {
		fmt.Println(err)
	}

}
